Materials by: John Blischak and other Software Carpentry instructors (Joshua R. Smith, Milad Fatenejad, Katy Huff, Tommy Guy and many more)
In this lesson we will cover how to write code that will execute only if specified conditions are met.
In [ ]:
x = 5
if x < 0:
print "x is negative"
In [ ]:
x = -5
if x < 0:
print "x is negative"
In [ ]:
x = 5
if x < 0:
print "x is negative"
else:
print "x in non-negative"
In [ ]:
x = 5
if x < 0:
print "x is negative"
elif x == 0:
print "x is zero"
else:
print "x is positive"
Be careful because the computer interprets comparisons very literally.
In [ ]:
'1' < 2
In [ ]:
True == 'True'
In [ ]:
False == 0
In [ ]:
'Bears' > 'Packers'
Indentation is a feature of python intended to make it more human-readable (though some people hate it). Some other programming languages use brackets to denote a command block. Python uses indentation. The amount of indentation doesn't matter, so long as everything in the same block is indented the same amount. The IPython notebook automatically converts tabs to 4 spaces, and any decent text editor will do the same (though not necessarily by default).
But you should pick a number of spaces (specifically 4, as this is the standard) and stick to that!
In [ ]:
def even_or_odd(x):
return "I have no idea!" # Fix that!